package com.freight.auth.service;

import com.freight.auth.form.RegisterBody;
import com.freight.common.core.constant.*;
import com.freight.common.core.constant.DictConstants;
import com.freight.common.core.utils.RsaUtils;
import com.freight.common.redis.service.RedisService;
import com.freight.tws.api.RemoteDriverClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.freight.common.core.domain.R;
import com.freight.common.core.exception.ServiceException;
import com.freight.common.core.utils.ServletUtils;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.core.utils.ip.IpUtils;
import com.freight.common.security.utils.SecurityUtils;
import com.freight.system.api.RemoteLogService;
import com.freight.system.api.RemoteUserService;
import com.freight.system.api.domain.SysLogininfor;
import com.freight.system.api.domain.SysUser;
import com.freight.system.api.model.LoginUser;

import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private RemoteLogService remoteLogService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    RemoteDriverClient remoteDriverClient;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 利用私钥解密密码
        try {
            password = RsaUtils.decryptByPrivateKey(password);
        } catch (Exception e) {
            throw new ServiceException("密码异常");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // 判断账号是否 密码错误尝试太多次导致账号锁定
        Boolean aBoolean = redisService.hasKey(Constants.LOGIN_ERROR + username);
        if(aBoolean) {
            int num = redisService.getCacheObject(Constants.LOGIN_ERROR + username);
            if(num >= Constants.LOGIN_ERROR_NUM) {
                long diff = redisService.getExpire(Constants.LOGIN_ERROR + username);
                long min = diff / 60 + 1;
                throw new ServiceException("账号已锁定，请" + min + "分钟后再试");
            }
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (R.FAIL == userResult.getCode() || StringUtils.isNull(userResult.getData()))
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户：" + username + " 不存在");
            loginErrorLock(username, "");
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (DictConstants.USER_STATUS.DELETED.getKey().equals(user.getDelFlag()))
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            loginErrorLock(username, "对不起，您的账号：" + username + " 已被删除");
        }
        if (DictConstants.USER_STATUS.DISABLE.getKey().equals(user.getStatus()))
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            loginErrorLock(username, "对不起，您的账号：" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword()))
        {
            recordLogininfor(username, Constants.LOGIN_FAIL, "密码错误");
            loginErrorLock(username, "");
        }
        // 登陆成功
        if(aBoolean) {
            redisService.deleteObject(Constants.LOGIN_ERROR + username);
        }
        recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 登陆异常锁定
     */
    private void loginErrorLock(String username, String msg) {
        int num = 1;
        if(redisService.hasKey(Constants.LOGIN_ERROR + username)) {
            num = redisService.getCacheObject(Constants.LOGIN_ERROR + username);
            num++;
            // 超过错误次数，锁定账号
            if(num >= Constants.LOGIN_ERROR_NUM) {
                redisService.setCacheObject(Constants.LOGIN_ERROR + username, num, Constants.LOGIN_ERROR_LOCK_TIME, TimeUnit.MINUTES);
                throw new ServiceException("登录失败次数太多，账号已锁定，请" + Constants.LOGIN_ERROR_LOCK_TIME + "分钟后再试");
            } else {
                // 错误计数
                long expire = redisService.getExpire(Constants.LOGIN_ERROR + username);
                redisService.setCacheObject(Constants.LOGIN_ERROR + username, num, expire, TimeUnit.SECONDS);
            }
        } else {
            redisService.setCacheObject(Constants.LOGIN_ERROR + username, num, 12L, TimeUnit.HOURS);
        }
        throw new ServiceException(StringUtils.isNotBlank(msg) ? msg : "登录失败，还剩" + (Constants.LOGIN_ERROR_NUM - num) + "次尝试机会");
    }

    public void logout(String loginName)
    {
        recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(RegisterBody registerBody)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(registerBody.getUsername(), registerBody.getPassword()))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if(remoteDriverClient.getDriverByPhone(registerBody.getUsername()) != null){
            throw new ServiceException("手机号已注册为司机, 无法注册货源方");
        }
        if (registerBody.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH
                || registerBody.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (registerBody.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || registerBody.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        //判断验证码是否正确
        String verifyCode = redisService.getCacheObject(SmsConstants.CACHE_SMS_VERFY_CODE + registerBody.getUsername());
        if(verifyCode == null) {
            throw new ServiceException("验证码已过期");
        }
        if(!verifyCode.equals(registerBody.getCode())) {
            throw new ServiceException("短信验证码错误");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(registerBody.getUsername());
        sysUser.setNickName(registerBody.getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
        sysUser.setUserType(DictConstants.USER_TYPE.HYF.getKey());
        sysUser.setCreateBy(registerBody.getUsername());
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogininfor(registerBody.getUsername(), Constants.REGISTER, "注册成功");
    }

    /**
     * 记录登录信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息内容
     * @return
     */
    public void recordLogininfor(String username, String status, String message)
    {
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        logininfor.setMsg(message);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
        {
            logininfor.setStatus("0");
        }
        else if (Constants.LOGIN_FAIL.equals(status))
        {
            logininfor.setStatus("1");
        }
        remoteLogService.saveLogininfor(logininfor, SecurityConstants.INNER);
    }
}